package org.hxzon.demo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class Server {

	public void start() {
		try {
			ServerSocketChannel serverChannel = ServerSocketChannel.open();

			serverChannel.socket().bind(new InetSocketAddress(80));
			serverChannel.configureBlocking(false);
			Selector selector = Selector.open();
			serverChannel.register(selector, SelectionKey.OP_ACCEPT);
			while (true) {
				int n = selector.select();

				if (n == 0) {
					continue; // nothing to do
				}

				Iterator<SelectionKey> it = selector.selectedKeys().iterator();

				while (it.hasNext()) {
					SelectionKey key = it.next();

					if (key.isAcceptable()) {
						ServerSocketChannel server = (ServerSocketChannel) key.channel();
						SocketChannel channel;
						channel = server.accept();
						channel.configureBlocking(false);
						channel.register(selector, SelectionKey.OP_READ);
					}

					if (key.isReadable()) {
						process(key);
					}

					it.remove();
				}
			}
		} catch (IOException e) {
			throw new ServerException(e);
		}
	}

	private void process(SelectionKey key) {

		try {
			SocketChannel socketChannel = (SocketChannel) key.channel();
			int count;

			ByteBuffer buffer = ByteBuffer.allocate(20 * 1024);
			while ((count = socketChannel.read(buffer)) > 0)
				;
			CmdHeader cmdHeader = new CmdHeader(buffer);
			switch(cmdHeader.cmd){
			case CmdHeader.RequestDownload:{
				download();
			}
			case CmdHeader.RequestEcho:{
				echo();
			}
			}
		} catch (IOException e) {
			throw new ServerException(e);
		}

	}

	private void download() {
		System.out.println("download file");
	}
	private void echo(){
		
	}

	public static void main(String args[]) {
		Server server = new Server();
		server.start();
	}
}
